<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.author"
        placeholder="请输入作者"
        style="width: 200px;"
        class="filter-item"
      />
      <el-select
        v-model="listQuery.status"
        placeholder="请选择状态"
        clearable
        style="width: 90px"
        class="filter-item"
      >
        <el-option
          v-for="item in selectOptions"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >查询</el-button>
      <el-button
        v-waves
        class="filter-item"
        type="info"
        icon="el-icon-refresh"
        @click="handleReset"
      >重置</el-button>
      <el-button
        style="float: right;"
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >新增</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" prop="id" align="center" width="200px">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Date" width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Author" width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.author }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Status" class-name="status-col" width="200px">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusTypeFilter">{{ scope.row.status | statusFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Actions" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
          <!-- <el-button size="mini" type="danger" @click="handleDelete(row.id)">
            删除
          </el-button>-->
          <el-popover placement="top" width="160" v-model="row.visible">
            <p>你确定删除吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="row.visible = false">取消</el-button>
              <el-button
                type="primary"
                size="mini"
                @click="row.visible = false;handleDelete(row.id)"
              >确定</el-button>
            </div>
            <el-button slot="reference" size="mini" type="danger">删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="类型" prop="status">
          <el-select v-model="temp.status" class="filter-item" placeholder="请选择">
            <el-option
              v-for="item in selectOptions"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Date" prop="timestamp">
          <el-date-picker
            v-model="temp.timestamp"
            type="datetime"
            placeholder="Please pick a date"
          />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="temp.author" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">退出</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?create():update()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// import { fetchList, fetchPv, createArticle, updateArticle } from '@/api/article'
import {
  fetchList,
  createData,
  updateData,
  deleteById,
  postData
} from "@/api/bdc/manual-operate";
import waves from "@/directive/waves"; // waves directive
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { setInterval } from 'timers';

const selectOptions = [
  { key: 0, label: "正常" },
  { key: 1, label: "维护" },
  { key: 2, label: "异常" }
];

// arr to obj, such as { CN : "China", US : "USA" }
// const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
//   acc[cur.key] = cur.display_name
//   return acc
// }, {})
export default {
  name: "ManualOperate",
  components: { Pagination },
  directives: { waves },
  filters: {
    statusTypeFilter(status) {
      const statusMap = {
        0: "success",
        1: "info",
        2: "danger"
      };
      return statusMap[status];
    },
    statusFilter(status) {
      const statusMap = {
        0: "正常",
        1: "维护",
        2: "异常"
      };
      return statusMap[status];
    }
  },
  data() {
    return {
      // 查询模块
      listQuery: {
        page: 1,
        limit: 20,
        status: undefined,
        author: undefined
      },
      selectOptions: selectOptions,
      // 表格显示
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      // 编辑模态窗
      temp: {
        id: undefined,
        status: 0,
        timestamp: null,
        author: ""
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "新增"
      },
      rules: {
        status: [{ required: true, message: "必填", trigger: "change" }],
        timestamp: [
          { type: "date", required: true, message: "必填", trigger: "change" }
        ],
        author: [{ required: true, message: "必填", trigger: "blur" }]
      },
      // websocket
      websocket: null,
      websocketReconnect: false,
      baseUrl: ""
    };
  },
  created() {
    // this.getList();
    console.log('this.$store', this.$store)
    this.baseUrl = process.env.VUE_APP_BASE_API;
  },
  destroyed() {

  },
  methods: {
    getList() {
      this.listLoading = true;
      fetchList(this.listQuery).then(res => {
        // console.log(res);
        if (res.code == 20000) {
          this.list = this.formatListData(res.data);
          this.total = res.data.length;
        } else {
          this.$message.error("服务器内部错误！");
        }
        this.listLoading = false;
        // setTimeout(() => {
        //   this.listLoading = false
        // }, 1000)
      });
    },
    formatListData(list) {
      list.forEach(element => {
        element.visible = false;
        return element;
      });
      return list;
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    // 重置
    handleReset() {
      this.listQuery = {
        page: 1,
        limit: 20,
        status: undefined,
        author: undefined
      };
    },
    // 重置模态窗数据
    resetTemp() {
      this.temp = {
        id: undefined,
        status: 0,
        timestamp: new Date(),
        author: ""
      };
    },
    // 新增
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    // 新增提交
    create() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.temp.id =
            parseInt(Math.random() * 100) * parseInt(Math.random() * 100); // mock a id
          createData(this.temp).then(res => {
            if (res.code === 20000) {
              this.dialogFormVisible = false;
              this.getList();
            } else {
              this.dialogFormVisible = false;
              this.$message.error(res.message);
            }
          });
        }
      });
    },

    // 编辑
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    // 编辑提交
    update() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp);
          tempData.timestamp = +new Date(tempData.timestamp); // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateData(tempData).then(res => {
            if (res.code === 20000) {
              this.dialogFormVisible = false;
              this.getList();
            } else {
              this.dialogFormVisible = false;
              this.$message.error(res.message);
            }
          });
        }
      });
    },
    // 删除
    handleDelete(id) {
      deleteById(id).then(res => {
        if (res.code === 20000) {
          this.getList();
        } else {
          this.$message.error("服务器内部错误");
        }
      });
    },
    initWebSocket() {
      //初始化weosocket
      this.websocket = new WebSocket(
        this.baseUrl.replace("http", "ws") + "/websocket/line|3000|01"
      );
      this.websocket.onopen = () => {
        console.log("Socket 已打开");
        this.websocket.send("消息发送测试(From Client)");
      };
      this.websocket.onerror = function() {
        console.log("Socket发生了错误");
        this.reconnectWebSocket();
      };
      this.websocket.onmessage = function(msg) {
        console.log(msg.data);
      };
      this.websocket.onclose = () => {
        console.log("Socket已关闭");
      };
    },
    //重连 待测试有问题，可能启动多个websocket
    reconnectWebSocket() {
      // reconnect重连会多次触发，所以需要给重连加一把锁，当一个重连正在执行的时候，无法再触发一次重连
      if (this.websocketReconnect) return;
      this.websocketReconnect = true;
      setTimeout(() => {
        console.log(new Date().getMinutes() + ":" + new Date().getSeconds());
        this.initWebSocket();
        this.websocketReconnect = false;
      }, 2000);
    }
  }
};
</script>
